namespace Digitalmes.Application.Sys.Orgs.Commands;

/// <summary>
/// 更新机构命令。
/// </summary>
/// <param name="Org">机构</param>
public record UpdateOrgCommand(long Id, SysOrgDto Org) : IRequest<IResult<bool>>;

internal sealed class UpdateOrgCommandHandler(IRepository<SysOrg> repo) : IRequestHandler<UpdateOrgCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(UpdateOrgCommand request, CancellationToken cancellationToken)
    {
        // 检查机构代码是否已存在。
        if (await repo.IsAnyAsync(m => m.Code == request.Org.Code && m.Id != request.Id, cancellationToken))
        {
            return Result.Failure("部门编号已存在");
        }

        var org = await repo.GetByIdAsync(request.Id, cancellationToken);
        if (org == null)
        {
            return Result.Failure("未找到要更新的部门");
        }

        org.Name = request.Org.Name;
        org.Order = request.Org.Order;
        org.Remark = request.Org.Remark;
        org.Status = request.Org.Status;

        var ok = await repo.UpdateAsync(org, m => new {
            m.Name,
            m.Order,
            m.Remark,
            m.Status,
            m.UpdatedBy,
            m.UpdatedTime,
        }, cancellationToken);
        return Result.From(ok);
    }
}

